import * as echarts from 'echarts';
import { DatePicker, Layout, message, Tabs } from "antd";
import locale from 'antd/es/date-picker/locale/zh_CN';
import moment from "moment";
import { useCallback, useEffect, useState } from "react";
import { getAccountByDateAPI } from "../../api";
import { AccountType, DateFilterType, IAccount } from "../../interface";
import style from './index.module.css'
import LineChart from '../charts/lineChart';
import PieChart, { IPieChartData } from '../charts/pieChart';

const { Header, Content } = Layout;
const { TabPane } = Tabs;


interface ChartData {
    expend: number
    income: number
}
interface LineChartDateWithData {
    [k: string]: ChartData
}
interface PieChartCategoryWithData {
    [AccountType.expend]: {
        [k: string]: IPieChartData
    }
    [AccountType.income]: {
        [k: string]: IPieChartData
    }
}

const Statistics: React.FC = () => {

    const [dateType, setDateType] = useState(DateFilterType.month);
    const [currentDate, setCurrentDate] = useState(new Date());

    // 日期数据
    const [accountDateData, setAccountDateData] = useState<string[]>([]);
    // 日期支出数据
    const [accountDateExpendData, setAccountDateExpendData] = useState<number[]>([]);
    // 日期收入数据
    const [accountDateIncomeData, setAccountDateIncomeData] = useState<number[]>([]);
    // 分类支出数据
    const [accountCategoryExpendData, setAccountCategoryExpendData] = useState<IPieChartData[]>([]);
    // 分类收入数据
    const [accountCategoryIncomeData, setAccountCategoryIncomeData] = useState<IPieChartData[]>([]);


    // 更改条件重新获取数据
    useEffect(() => {
        getAccountByDate();
    }, [dateType, currentDate]);
    // 根据日期获取数据
    const getAccountByDate = () => {
        getAccountByDateAPI(currentDate, dateType)
        .then(res => {
            if (res.data.code === 0) {
                // console.log(res.data.data.accounts)
                filterData(res.data.data.accounts);
            }
            else {
                throw new Error(res.data.message);
            }
        })
        .catch(e => {
            console.log(e)
            message.error(e.message)
        })
    }
    // 过滤数据,分成支出和收入
    const filterData = (accounts: IAccount[]) => {
        // 用对象处理相同日期的数据
        let dateData: LineChartDateWithData = {};
        let categoryData: PieChartCategoryWithData = {
            [AccountType.expend]: {},
            [AccountType.income]: {},
        };
        for (let i = 0; i < accounts.length; i++) {
            let nowData = accounts[i];
            let date = new Date(nowData.date_time).toLocaleDateString().split('/').join('-');
            // console.log(nowData)
            // 与上次数据相同日期
            if (!dateData[date]) {
                dateData[date] = {
                    expend: 0,
                    income: 0
                }
            }
            if (nowData.account_type === AccountType.expend) {
                dateData[date].expend += nowData.amount
            }
            else {
                dateData[date].income += nowData.amount
            }

            // 分类数据
            if (!categoryData[nowData.account_type][nowData.category_name]) {
                categoryData[nowData.account_type][nowData.category_name] = {
                    value: 0,
                    name: nowData.category_name
                }
            }
            categoryData[nowData.account_type][nowData.category_name].value += nowData.amount;
        }
        // 折现图数据转成数组
        let xDateLine: string[] = [];
        let yExpendLine: number[] = [];
        let yIncomeLine: number[] = [];
        for (let date in dateData) {
            xDateLine.push(date);
            yExpendLine.push(dateData[date].expend)
            yIncomeLine.push(dateData[date].income)
        }
        setAccountDateData(xDateLine)
        setAccountDateExpendData(yExpendLine)
        setAccountDateIncomeData(yIncomeLine)
        // 饼状图数据转数组
        let expendPie: IPieChartData[] = []
        let incomePie: IPieChartData[] = []
        for (let key in categoryData[AccountType.expend]) {
            expendPie.push(categoryData[AccountType.expend][key])
        }
        for (let key in categoryData[AccountType.income]) {
            incomePie.push(categoryData[AccountType.income][key])
        }
        setAccountCategoryExpendData(expendPie)
        setAccountCategoryIncomeData(incomePie)
    }

    return (
        <Layout className={style.statistics}>
            <Header className={style.statistics_header}>
                <DatePicker 
                    locale={locale} 
                    className={style.statistics_datepicker} 
                    value={moment(currentDate)}
                    onChange={(date, dateString) => setCurrentDate(new Date(dateString))} 
                    picker={dateType}
                    allowClear={false}
                    style={{minWidth: 120}}
                />
                <Tabs 
                    className={style.statistics_tab} 
                    defaultActiveKey={DateFilterType.month}
                    type="card" 
                    tabBarStyle={{margin: 0}}
                    onChange={(activekey) => setDateType(activekey as DateFilterType)}
                >
                    <TabPane tab="月" key={DateFilterType.month}></TabPane>
                    <TabPane tab="年" key={DateFilterType.year}></TabPane>
                </Tabs>
            </Header>
            <Content className={style.statistics_content}>
                {
                    accountDateData.length < 1 || (accountDateExpendData.length < 1 && accountDateIncomeData.length < 1) ?
                        <div className={style.no_data}>无账单</div> : 
                        <>
                            <LineChart title="趋势统计" x={accountDateData} y={{[AccountType.expend]: accountDateExpendData,[ AccountType.income]: accountDateIncomeData}} />
                            <div className={style.statistics_category}>
                                <PieChart title={AccountType.expend} data={accountCategoryExpendData} />
                                <PieChart title={AccountType.income} data={accountCategoryIncomeData} />
                            </div>
                        </>
                }
            </Content>
        </Layout>
    )
}


export default Statistics;

